using System;
using System.Configuration;
using System.IO;
using System.Reflection;

namespace BSDS.Core.Infrastructure.Configuration
{
    public class BingKeyLazyLoader : IBingKey
    {
        private readonly string bingKeyFilename;

        private string bingKey;

        public string Value
        {
            get
            {
                if (string.IsNullOrEmpty(bingKey))
                {
                    LoadBingKeyFromFile();
                }

                return bingKey;
            }
        }

        public BingKeyLazyLoader(string bingKeyFilename)
        {
            this.bingKeyFilename = bingKeyFilename;
        }

        private void LoadBingKeyFromFile()
        {
            var binKeyFilePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, bingKeyFilename);

            using (var reader = new StreamReader(binKeyFilePath))
            {
                string firstLine = reader.ReadLine();

                if (firstLine == null)
                {
                    throw new ConfigurationErrorsException("No data found in bing key file.");
                }

                bingKey = firstLine.Trim();
            }
        }

        public override string ToString()
        {
            return Value;
        }
    }
}